<template>
  <div class="body">
    <div class="editAlert" v-if="alertState">
      <div class="Pop_title">
        {{ alertTitle }}
      </div>
      <div class="formBox">
        <el-form label-width="100px" :model="editForm" ref="formRef" class="search_form" :rules="editFormRoules">
          <div class="Pop_half">
            <el-form-item label="选择店铺" label-position="left" prop="foodshop_id">
              <el-select v-model.trim="editForm.foodshop_id" placeholder="请选择店铺" style="width: 240px">
                <el-option v-for="item in storeData" :key="item.id" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="选择分类" label-position="left" prop="foodproducttype_id">
              <el-select v-model.trim="editForm.foodproducttype_id" multiple filterable allow-create default-first-option
                :reserve-keyword="false" placeholder="请选择店铺类型" style="width: 240px">
                <el-option v-for="item in typeData" :key="item.id" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="商品名称" label-position="left" prop="title">
              <el-input v-model.trim="editForm.title" placeholder="请输入商品名称" class="search_input" />
            </el-form-item>
            <el-form-item label="店铺图片" label-position="left" prop="img">
              <div class="avatar-uploader">
                <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1"
                  :on-change="handleFileChange" :on-remove="handleRemove" :on-preview="handleimgsPreview"
                  :file-list="fileimg" :class="{ 'hide-upload': fileimg.length > 0 }">
                  <template v-if="fileimg.length === 0">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </template>
                  <template v-else>
                    <img class="avatar" :src="fileimg[0].url" alt="头像" />
                    <span class="avatar-actions">
                      <span class="avatar-delete" @click.stop="handleRemove(fileimg[0])">
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </span>
                    </span>
                  </template>
                </el-upload>
              </div>
            </el-form-item>
          </div>
          <div class="Pop_half">
            <el-form-item label="商品介绍" label-position="left" prop="desc">
              <el-input v-model.trim="editForm.desc" style="width: 240px" :rows="2" type="textarea" placeholder="请输入介绍" />
            </el-form-item>
            <el-form-item label="商品原价" label-position="left" prop="old_price">
              <el-input-number v-model.trim="editForm.old_price" :min="1" :max="10000" />
            </el-form-item>
            <el-form-item label="商品现价" label-position="left" prop="price">
              <el-input-number v-model.trim="editForm.price" :min="1" :max="10000" />
            </el-form-item>
            <el-form-item label="商品销量" label-position="left" prop="quanitiy">
              <el-input-number v-model.trim="editForm.quantity" :min="1" :max="100000" />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="footer_btn">
        <el-button type="primary" @click="affirm()">确认</el-button>
        <el-button class="rigthBtn" @click="cancel">取消</el-button>
      </div>
    </div>


    <div class="content" v-if="!alertState">
      <div class="search_box">
        <el-form label-width="auto" :model="search" class="search_form">
          <el-form-item label="分类标题" label-position="top">
            <el-input v-model="search.title" placeholder="请输入标题" class="search_input input_height" @input="searchData" />
          </el-form-item>
          <el-form-item label="创建时间" label-position="top">
            <el-date-picker type="daterange" v-model="search.time" size="default" start-placeholder="开始时间"
              end-placeholder="结束时间" format="YYYY/MM/DD" value-format="YYYY-MM-DD" unlink-panels
              @change="searchData"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div class="line"></div>
      <div class="operateBtn">
        <el-button type="primary" class="button_height" @click="addAlter">添加</el-button>
        <el-button type="danger" class="button_height" @click="delePop(selectedIds)">批量删除</el-button>
      </div>
      <el-table :data="pageCount" style="width: 100%" class="table" @selection-change="checkall">
        <el-table-column type="selection" />
        <el-table-column prop="shoptitle" label="店铺名称" align="center" />
        <el-table-column prop="title" label="商品名称" align="center" />
        <el-table-column label="介绍" align="center" width="210">
          <template #default="scope">
            <p class="introduce">{{ scope.row.desc }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="销量" align="center" width="80" />
        <el-table-column label="上架/下架" align="center">
          <template #default="scope">
            <el-switch @change="changeStatus(scope.row)" v-model="scope.row.status" :active-value="1"
              :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" align="center" />
        <el-table-column label="图片" align="center" width="80">
          <template #default="scope">
            <div class="demo-image__preview">
              <el-image style="width: 40px; height: 40px"
                :src="scope.row.img.startsWith('http') ? scope.row.img : url + scope.row.img" :zoom-rate="1.2"
                :max-scale="7" :min-scale="0.2"
                :preview-src-list="[scope.row.img.startsWith('http') ? scope.row.img : url + scope.row.img]"
                show-progress fit="cover" preview-teleported />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="创建时间" align="center" />
        <el-table-column prop="createtime" label="操作" align="center">
          <template #default="scope">
            <div class="operate_box">
              <p class="edit" @click="editAlter(scope.row)">编辑</p>
              <p class="delete" @click="delePop([scope.row.id])">删除</p>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="custom_container">
        <el-pagination @size-change="pageNum" @current-change="pageChange" :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="sizes, prev, pager, next, jumper"
          :total="pageData.length" class="custom_pagination" />
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { url } from '/@/api/url';
import { fileUpload } from '/@/api/login';
import { ElMessage, FormInstance, FormRules, UploadFile } from 'element-plus';
import { ShopList, ShopAdd, ShopDel, ShopStatue } from '/@/api/food/food_product/index';
// 导入店铺列表
import { foodShopList } from '/@/api/food/food_shop/index';
// 商品分类列表
import { food_shoptypeList } from '/@/api/food/food_shoptype/index';
import { ElMessageBox } from 'element-plus';
import { debounce } from 'lodash-es';


interface FoodType {
  id: number;
  title: string;
  createtime: string;
}

const data = ref<FoodType[]>([]);
const pageData = ref<FoodType[]>([]);
// 分页页数
const currentPage = ref(1);
// 一页的数据
const pageSize = ref(10);
const imgsState = ref(false);
// 店铺列表
const storeData = ref<FoodType[]>([]);
// 分类列表
const typeData = ref<FoodType[]>([]);
// 弹窗title
const alertTitle = ref('');
const search = reactive({
  title: '',
  time: '',
})

const editForm = reactive({
  uid: '',
  foodproducttype_id: [],
  title: '',
  time: '',
  sort: 0,
  img: '',
  quantity: 0,
  old_price: 0,
  price: 0,
  status: 0,
  foodshop_id: '',
  desc: '',
  id: '',
});

const editFormRoules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
  ],
  foodproducttype_id: [
    { required: true, message: '请选择分类', trigger: 'blur' },
  ],
  img: [
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],
  quantity: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
  ],
  old_price: [
    { required: true, message: '请输入商品原价', trigger: 'blur' },
  ],
  foodshop_id: [
    { required: true, message: '请选择所属店铺', trigger: 'blur' },
  ],
  desc: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
  ],
})


const alertState = ref(false);
const formRef = ref<FormInstance>();

const getData = () => {
  ShopList({ uid: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id }).then((res: any) => {
    console.log(res);
    data.value = res.data;
    pageData.value = res.data;
    getStore();
    getType();
  });
}
getData();
// 店铺列表接口
const getStore = () => {
  foodShopList({ uid: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id }).then((res: any) => {
    storeData.value = res.data;
  });
}
// 分类列表接口
const getType = () => {
  food_shoptypeList().then((res: any) => {
    console.log(res)
    typeData.value = res.data;
  })
}
// 计算当前页码的起始索引和结束索引，并返回对应区间的数据
const pageCount = computed(() => {
  // 计算起始索引，基于当前页码和每页大小
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return pageData.value.slice(start, end);
});
/* 分页改变 */
const pageChange = (val: number) => {
  currentPage.value = val;
};
/* 分页大小改变 */
const pageNum = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 添加弹窗
const addAlter = () => {
  alertState.value = true;
  editForm.id = '';
  alertTitle.value = '添加';
}

// 编辑弹窗显示
const editAlter = (item: any) => {
  alertTitle.value = '编辑';
  alertState.value = true;
  editForm.title = item.title;
  editForm.sort = item.sort;
  editForm.img = item.img;
  editForm.quantity = item.quantity;
  editForm.old_price = item.old_price;
  editForm.price = item.price;
  editForm.desc = item.desc;
  editForm.status = item.status;
  editForm.foodshop_id = item.foodshop_id;
  editForm.foodproducttype_id = item.foodproducttype_id.split(',').map(Number);
  const img = item.img.startsWith(url) ? item.img : url + item.img;
  fileimg.value = img
    ? [
      {
        uid: Date.now(),
        name: 'avatar',
        url: img,
        status: 'success',
      },
    ]
    : [];
  editForm.id = item.id;
}

// 确认函数
const affirm = async () => {
  formRef.value?.validate((valid, fields) => {
    if (valid) {
      ShopAdd({
        id: editForm.id,
        uid: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id,
        title: editForm.title,
        sort: editForm.sort,
        img: editForm.img,
        quantity: editForm.quantity,
        old_price: editForm.old_price,
        price: editForm.price,
        desc: editForm.desc,
        status: editForm.status,
        foodshop_id: editForm.foodshop_id,
        foodproducttype_id: editForm.foodproducttype_id.join(),
      }).then((res) => {
        console.log(res);
        ElMessage({
          message: res.msg,
          type: 'success',
        })
        alertState.value = false;
        getData();
      });
    }
  });
}
// 状态修改函数
const changeStatus = debounce((item: any) => {
  ShopStatue({
    uid: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id,
    ids: item.id,
    status: item.status
  }).then((response) => {
    if (response.code === 1) {
      ElMessage.success(response.msg);
      formRef.value?.resetFields();
      getData();
    }
  })
    .catch((error) => {
      console.error('请求失败:', error);
    });
}, 1000);

// 获取全选的id
const selectedIds = ref<any[]>([]);
const checkall = (val: any) => {
  selectedIds.value = val.map((item: any) => item.id).filter((id: number) => id);
};

// 删除函数
const delePop = (id: any) => {
  if (id.length <= 0) {
    ElMessage.error('请选择要删除的数据')
    return;
  }
  ElMessageBox.confirm("确定要删除这些数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ShopDel({
      uid: JSON.parse(localStorage.getItem('userinfo') || '').userinfo.id,
      ids: id.join()
    }).then((res) => {
      if (res.code == 1) {
        ElMessage.success(res.msg);
        getData();
      }
    }).catch((error: any) => {
      console.log(error);
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

// 取消函数
const cancel = () => {
  alertState.value = false;
  formRef.value?.resetFields();
  fileimg.value = [];
}

// 图片上传
const fileimg = ref<UploadFile[]>([])  // 关键：维护文件列表
// 图片预览的路径
const dialogImageUrl = ref(<any>[]);
// 图片上传
const handleFileChange = async (file: UploadFile) => {
  // 创建本地预览
  file.url = URL.createObjectURL(file.raw!);
  fileimg.value = [file];
  // 上传到服务器
  const formData = new FormData();
  formData.append('file', file.raw!);
  console.log(formData);
  fileUpload(formData).then(res => {
    editForm.img = res.data.url;
    formRef.value?.clearValidate('img');
  }).catch((error) => {
    fileimg.value = [];
    editForm.img = '';
    ElMessage.error('上传失败');
    handleRemove();
    formRef.value?.validateField('img');
  });
}
// 图片删除
const handleRemove = (file?: UploadFile) => {
  fileimg.value = [];
  editForm.img = '';
  formRef.value?.validateField('img');
};

// 图片预览
const handleimgsPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url; // 优先显示服务器URL
  imgsState.value = true;
};

// 搜索函数
const searchData = () => {
  pageData.value = data.value;
  const filteredData = () => {
    // 无搜索词时返回全部数据
    if (search.title == '' && search.time.length == 0) {
      return (pageData.value = data.value);
    }
    return pageData.value.filter((item) => {
      console.log(item.createtime);

      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch =
        !search.title || (item.title && item.title.toLowerCase().includes(search.title.toLowerCase()));
      const timeMatch =
        search.time.length == 0 ||
        (item.createtime >= search.time[0] && item.createtime <= search.time[1]);
      return nameMatch && timeMatch;
    });
  };
  pageData.value = filteredData();
};


</script>

<style scoped>
.body {
  padding: 30px;
}

.content {
  position: relative;
  padding: 30px;
  background-color: white;
}

.line {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin: 20px 0;
}

.search_form {
  width: 100%;
  display: flex;
  margin-bottom: -22px;
}

.search_input {
  width: 240px;
  margin-right: 30px;
}

.input_height{
  height: 33px;
}

.button_height {
  height: 30px;
}

.operateBtn {
  display: flex;
  margin-top: 10px;
}

.label {
  margin-top: 10px;
}

.introduce {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.operate_box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit {
  color: #409EFF;
  cursor: pointer;
  margin: 0px 10px;
}

.delete {
  color: #F56C6C;
  cursor: pointer;
  margin: 0px 10px;
}

.custom_container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.editAlert {
  position: absolute;
  width: 100%;
  overflow: auto;
  background-color: white;
  top: 0;
  right: 0;
  z-index: 30;
}

.Pop_title {
  padding: 2%;
  border-bottom: 1px solid #ddd;
}

.formBox {
  padding: 2%;
}

.Pop_half {
  margin-left: 9%;
}

.footer_btn {
  display: flex;
  justify-content: end;
  margin-top: 5%;
  margin-right: 5%;
  margin-bottom: 5%;
}

.rigthBtn {
  margin-left: 5%;
}



.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

/* 隐藏上传按钮当有图片时 */
.hide-upload :deep(.el-upload) {
  display: none;
}

/* 在全局或组件样式添加 */
.avatar-uploader :deep(.el-upload-list__item) {
  transition: none !important;
}

.map_container {
  width: 240px;
  height: 180px;
}

.preview-img {
  width: 100%;
}
</style>